/*
Copyright 2014 Yury Kharlamov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated Inversion-Of-Control container
https://code.google.com/p/gen-ioc/

* * *

Controller class. Uses Worker to do some lengthy job.
Receives events from Worker upon job completeion.
*/
#include "stdafx.h"
#include "GenIOC/EventSourceBase.h"
#include "StateMachine/state_machine.h"
#include "IController.h"
#include "IWorker.h"
#include "IWorkerEventsConsumer.h"
#include "INotSingleton.h"
#include "IErrorReport.h"
#include "id_generator.h"
#include "ControllerBase.h"


namespace SeqState
{
	enum Enum{ Init, WaitFinish, Done, ErrorOccurred };
};

using namespace state_machine;

class Controller : public ControllerBase, public ASM<SeqState::Enum>
{
public:
	struct StartWork{};

	Controller()
		:ASM(SeqState::Init)
		, m_id(IdGenerator::GetNextId())
	{
		State<SeqState::Enum> Init(SeqState::Init), WaitFinish(SeqState::WaitFinish)
			, Done(SeqState::Done), ErrorOccurred(SeqState::ErrorOccurred), _ = State<SeqState::Enum>::Any();
		*this +=
			Init + StartWork() > WaitFinish - [=]{ printf("Start load\n"); m_Worker->Download(); Create_INotSingleton(); },
			WaitFinish + WorkResult() > Done - [=]{printf("Dowload result\n"); },
			_ + Error() > ErrorOccurred - [=](const Error e){ std::stringstream s; s << "Error in Controller: " << e.Text(); m_IErrorReport->ReportError(s.str()); };
		SetOnAfterTransition([](SeqState::Enum from, SeqState::Enum to)
		{
			printf("Controller: %i->%i\n", from, to);
		});
	}
	~Controller()
	{
		printf("Destroyed %i\n", this);
	}
	void Run() override
	{
		printf("%i\n", this);
		m_IWorkerEventsConsumer->Start();
		QueueEvent(StartWork());
	}

	int GetId()
	{
		return m_id;
	}

	void PushEvent(const boost::any& event) override
	{
		QueueEvent(event);
	}
private:
	std::shared_ptr<IWorker> m_dnl;
	int m_id;
};

std::shared_ptr<IObject> CreateController()
{
	return std::static_pointer_cast<IController>(std::make_shared<Controller>());
}
